
const request = require('request');
const moment = require('moment');
const apiUrl = 'http://wms.auewecanberra.com/api/';
var token = require('./token');
const co = require('co');
const Promise = require('promise');
function check_status_code(code) {
  if (code >= 400) {
    return false;
  } else {
    return true;
  }
}
module.exports = {

  //订单预生成，返回订单id
  preOrder: function (json, call) {
      token.getApiTokenCall(function (tokenN) {
        request({
          url: apiUrl+'sales/',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: tokenN,
          },
          form: json,
        }, function (err, resp, body) {
          if (err) return call(err);
          if (check_status_code(resp.statusCode)) {
            return call(body);
          } else {
            return call('error occured, status code:',resp.statusCode);
          }
        })
      })
  },

  updateOrder: function (order_id, json, call) {
    if (requireNonNull(order_id)) {
      token.getApiTokenCall(function (token) {
        request({
          url: apiUrl+'sales/'+order_id,
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            Authorization: token,
          },
          form: json,
        }, function (err, resp, body) {
          if (err) return call(err);
          if (check_status_code(resp.statusCode)) {
            return call(body);
          } else {
            return call('error occured, status code:',resp.statusCode);
          }
        })
      })
    } else {
      return call('order id is null');
    }
  },

  //通过订单id获取订单信息
  getOrderDetail: function (id, call) {
    if (requireNonNull(id)) {
      var reqUrl = apiUrl+'sales/?id='+id;
      console.log('order id:',id,reqUrl);
      token.getApiTokenCall(function (result) {
        request({
          url: reqUrl,
          method: 'GET',
          headers: {
            Authorization: result
          }
        }, function (err, resp, body) {
          if (err) return call(err);
          if (check_status_code(resp.statusCode)) {
            return call(body);
          } else {
            return call('error occured, status code:',resp.statusCode);
          }
        })
      })
    } else {
      return call('id is null');
    }
  },

  get_order_specs: function (order_id, call) {
    if (requireNonNull(order_id)) {
      token.getApiTokenCall(function (token) {
        request({
          url: apiUrl+'sales/'+order_id+'/specs/',
          method: 'GET',
          headers: {
            Authorization: token
          }
        }, function (err, resp, body) {
          if (err) return call(err);
          if (check_status_code(resp.statusCode)) {
            return call(body);
          } else {
            return call('error, code is:',resp.statusCode);
          }
        })

      })
    }
  },

  get_order_specs_sync: function (order_id) {
    return new Promise(function (resolve, reject) {
      token.getApiTokenCall(function (token) {
        request({
          url: apiUrl+'sales/'+order_id+'/specs/',
          method: 'GET',
          headers: {
            Authorization: token
          }
        }, function (err, resp, body) {
          if (err) reject(err);
          resolve(body);
        })
      })
    })
  },

  get_order_payment: function (order_id, call) {
    if (requireNonNull(order_id)) {
      token.getApiTokenCall(function (token) {
        request({
          url: apiUrl+'sales/'+order_id+'/payment/',
          method: 'GET',
          headers: {
            Authorization: token
          }
        }, function (err, resp, body) {
          if (err) return call(err);
          if (resp.statusCode < 400) {
            return call(body);
          } else {
            return call('err status code:', resp.statusCode);
          }
        })
      })
    }
  },

  //获取箱号，总价
  getBoxNo: function (id, call) {
    if (requireNonNull(id)) {
      var reqUrl = apiUrl+'sales/'+id+'/shipping_boxes/';
      token.getApiTokenCall(function (result) {
        request({
          url: reqUrl,
          headers: {
            Authorization: result
          }
        }, function (err, resp, body) {
          if (err) return call(err);
          return call(body);
        })
      })
    } else {
      return call('id is null');
    }
  },

  //用户确认价格，正式创建订单
  createOrder: function (json, call) {
    var reqBody = {
      id: json.id,
      order: JSON.stringify(json.order),
      order_specs: JSON.stringify(json.order_specs),
      order_shp_boxes: JSON.stringify([json.order_shp_boxes])
    };
    token.getApiToken(function (result) {
      request({
        url: apiUrl+'sales/'+json.id,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: result
        },
        body: reqBody,
      }, function (err, resp, body) {
        if (err) return call(err);
        return call(body);
      })
    })
  },

  //支付回调

  //上传支付
  upload_payment_info: function (order_id, payment, pay_method, json, call) {
    //TODO verify {order_id, payment, pay_method}
    token.getApiTokenCall(function (token) {
      request({
        url: apiUrl+'sales/'+order_id+'/payment/',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: token,
        },
        form: {
          payment: payment,
          pay_method: pay_method,
          remark : JSON.stringify(json)
        },
      }, function (err, resp, body){
        if (err) return call(err);
        return call(body);
      })
    })
  },

  get_customers_async: function () {
    return new Promise(function (resolve, reject) {
      token.getApiTokenCall(function (token) {
        request({
          url: apiUrl+'customers/',
          method: 'GET',
          headers: {
            Authorization: token
          }
        }, function (err, resp, body) {
          if (err) return reject(err);
          resolve(JSON.parse(body));
        })
      })
    })
  },

  get_customers: function (call) {
    token.getApiTokenCall(function (token) {
      request({
        url: apiUrl+'customers/',
        method: 'GET',
        headers: {
          Authorization: token
        }
      }, function (err, resp, body) {
        if (err) return call(err);
        return call(JSON.parse(body));
      })
    })
  },

  create_customer: function (json, call) {
    token.getApiTokenCall(function (token) {
      request({
        url: apiUrl+'customers/',
        method: 'POST',
        headers: {
          Authorization: token,
        },
        form: json,
      }, function (err, resp, body) {
        if (err) return call(err)
        if (resp.statusCode >= 400) {
          return call('error code is:',resp.statusCode,'content:', body);
        } else {
          return call(body);
        }
      })
    })
  },

  get_customer_by_id: function (customer_id, call) {
    //TODO verify customer_id
    token.getApiTokenCall(function (token) {
      request({
        url: apiUrl+'customers/'+customer_id,
        method: 'GET',
        headers: {
          Authorization: token,
        }
      }, function (err, resp, body) {
        if (err) return call(err);
        return call(JSON.parse(body));
      })
    })
  },

  get_customer_by_openid: function (openid, call) {
    token.getApiTokenCall(function (token) {
      request({
        url: apiUrl+'customers/?source_id='+openid,
        mehtod: 'GET',
        headers: {
          Authorization: token
        }
      }, function (err, resp, body) {
        if (err) return call(err);
        return call(JSON.parse(body));
      })
    })
  },

  get_customer_contacts: function (customer_id, call) {
    //verify cusomter_id
    if(requireNonNull(customer_id)){
      token.getApiTokenCall(function (token) {
        request({
          url: apiUrl+'customers/'+customer_id+'/contacts/',
          method: 'GET',
          headers: {
            Authorization: token
          }
        }, function (err, resp, body) {
          if (err) return call(err);
          return call(JSON.parse(body));
        })
      })
    }
  },

  create_customer_contact: function (customer_id, json, call) {
    //verify cusomter_id
    if(requireNonNull(customer_id)){
      token.getApiTokenCall(function (token) {
        request({
          url: apiUrl+'customers/'+customer_id+'/contacts/',
          method: 'POST',
          headers: {
            Authorization: token,
          },
          form: json,
        }, function (err, resp, body) {
          if (err) return call(err);
          console.log(resp.statusCode);
          if ( resp.statusCode == 200) {
            return call(JSON.parse(body));
          } else {
            return call(body);
          }
        })
      })
    }
  },

  get_contact_by_id: function (customer_id, contact_id, call) {
    //verify customer_id & contact_id
    if(typeof(customer_id) === 'undefined'){
      console.log('undefined customer_id occurs in get_contact_by_id, omit call');
      return;
    }
    if(typeof(contact_id) === 'undefined'){
      console.log('undefined contact_id occurs in get_contact_by_id, omit call');
      return;
    }

    token.getApiTokenCall(function (token) {
      request({
        url: apiUrl+'customers/'+customer_id+'/contacts/'+contact_id,
        mehtod: 'GET',
        headers: {
          Authorization: token
        }
      }, function (err, resp, body) {
        if (err) return call(err);
        console.log(resp.statusCode);
        return call(JSON.parse(body));
      })
    })
  },

  wechat_msg_notify: function (openid, url, json, call) {

  },

  get_order_detail_by_id: function (order_id, call) {

  },

  get_customer_orders_by_customer_id: function (customer_id, status, call) {
    // if (status == 'all') {
    //   var url = apiUrl+encodeURI('sales/?sort=-create_time, &customer=lk,%'+customer_id+'%');
    // } else {
    //   var url = apiUrl+encodeURI('sales/?sort=-create_time, &customer=lk,%'+customer_id+'%&status=lk,%'+Number(status)+'%');
    // }
    var q_criteria = '';
    switch (status) {
      case 'all':
        q_criteria = encodeURI('sales/?sort=-create_time, &customer=lk,%'+customer_id+'%');
        break;
      case 'pay':
        q_criteria = encodeURI('sales/?sort=-create_time, &customer=lk,%'+customer_id+'%&status=lk,%5%&pmt_status=lt,13');
        break;
      case 'deliver':
        q_criteria = encodeURI('sales/?sort=-create_time, &customer=lk,%'+customer_id+'%&status=lk,%10%&dlr_status=lt,40&pmt_status=gte,13');
        break;
      case 'receive':
        q_criteria = encodeURI('sales/?sort=-create_time, &customer=lk,%'+customer_id+'%&status=lk,%10%&pmt_status=gte,13&dlr_status=gte,40');
        break;
    }
    var url = apiUrl+q_criteria;
    console.log('uri is:', url);
    token.getApiTokenCall(function (token) {
      request({
        url: url,
        method: 'GET',
        headers: {
          Authorization: token
        }
      }, function (err, resp, body) {
        if (err) return call(err);
        if (resp.statusCode != 200) {
          return call(body);
        } else {
          return call(JSON.parse(body));
        }
      })
    })
  },

  get_order_history_by_id: function (order_id, call) {
    //TODO verify order_id
    token.getApiTokenCall(function (token) {
      request({
        url: apiUrl+'sales/'+order_id+'/history/',
        method: 'GET',
        headers: {
          Authorization: token
        }
      }, function (err, resp, body) {
        if (err) return call(err);
        if (resp.statusCode != 200) {
          return call(body);
        } else {
          return call(JSON.parse(body));
        }
      })
    })
  }
}

function requireNonNull(param){
  if( typeof(param) === 'undefined' || param === null || param === 'null') {
    return false;
  }
  else {
    return true;
  }
}

